<template>
<div style="display: block; ">
    <el-row>
        <el-col :span="10">
            <el-form ref="formInline" :model="formInline" :rules="ruleInline" style="float: left">
                <el-form-item prop="user" style="float: left">
                    <el-input type="text" v-model="formInline.user" placeholder="文章名字" style="float: left">文章名字</el-input>
                </el-form-item>
                <el-form-item prop="is_public" style="float: left;margin-left: 20px;">
                    <el-checkbox v-model="is_public" style="color:white">不公开</el-checkbox>
                </el-form-item>
                <el-form-item style="float: left">
                    <el-button @click="getArticles" type="primary" style="float: left;margin-left: 10px; ">查询</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="1">
            <div style="display: block;margin-top: 8px; font-size:15px; ">
                分类:
            </div>
        </el-col>
        <el-col :span="3" style="margin-left: 20px">
            <el-select v-model="currentGroup" placeholder="选择分组" @change="OnChangeGroup">
                <el-option v-for="item in this.docgroups" :key="item.Int" :label="item.Name" :value="item.Int"></el-option>
            </el-select>
        </el-col>
        <el-col :span="3">
            <el-select v-model="docType"  placeholder="分类" style="margin-left: 20px">
                <el-option v-for="item in this.doc_types" :key="item.id" :label="item.type_name" :value="item.id">
                </el-option>
            </el-select>
        </el-col>
    </el-row>

    <div style="display: inline-block;width: 100%;float: left;height: 100%;">
    <el-col :span="20" style="height: 100%;margin-right: 30px;">
    <el-tree
        :data="this.data"
        node-key="id"
        default-expand-all
        style="height: 100%; "
    >
    <span class="custom-tree-node" slot-scope="{ node, data }">
      <span>{{ node.label }}</span>
      <span>
        <el-button
            type="text"
            size="mini"
            @click="() => edit(node, data)" style="margin-left:20px">
          编辑文章
        </el-button>
        <el-button
            type="text"
            size="mini"
            @click="() => append(data)"  style="margin-left:20px">
          添加子文章
        </el-button>
        <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)"  style="margin-left:20px">
          删除文章
        </el-button>
        <el-button type="text" size="mini" @click="() => generate_show_url(node, data)" style="margin-left:20px">
            生成浏览外链
        </el-button>
        <el-button type="text" size="mini" @click="() => import_file_func(node, data)" style="margin-left:20px">
            导入文件
        </el-button>
      </span>
    </span>
    </el-tree>
    </el-col>
    </div>
   

    <el-dialog
    title="导入文件"
    :visible.sync="import_file"
    :with-header="false"
    :size=1080
    :before-close="handleCloseDraw"
    
>
<div class="container">
    <el-row style="margin-top: 10px;">
        <el-col :span="4" style="text-align:center;    display:table;">
            <p class="md-text1">上级文章:</p>
        </el-col>
        <el-col :span="10">
            <el-input placeholder="标题" v-model="file_add_title"></el-input>
        </el-col>
    </el-row>
    <el-row style="margin-top:30px;">
        <el-col :span="4" style="text-align:center;    display:table;">

        <el-upload
            class="upload-demo"
            ref="upload"
            :action="this.upload_url"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :before-upload="onBeforeUpload"
            :auto-upload="true"
            multiple
            :limit="100"
            :on-exceed="handleExceed"
        :file-list="fileList"
    >
    <el-button size="small" type="primary">选择文件</el-button>
    </el-upload>
    </el-col>
    <el-col :span="10">
        <el-input placeholder="文件路径" v-model="currentEditTitle"></el-input>
    </el-col>

    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
    </el-row>

</div>

</el-dialog>


    <el-drawer
        title="新增文章"
        :visible.sync="drawer"
        :with-header="false"
        :size=1256
        :before-close="handleCloseDraw"
    >
    <div class="container">
        <el-row style="margin-top: 10px;">
            <el-col :span="1" style="text-align:center;    display:table;">
                <p class="md-text1">标题:</p>
            </el-col>
            <el-col :span="3">
                <el-input placeholder="标题" v-model="currentEditTitle"></el-input>
            </el-col>
        </el-row>
        <el-row style="margin-top:30px;">
            <mavon-editor style="height: 600px;margin-left: 4px;" v-model="currentEditContent" :subfield=this.subfield  
                            :editable=this.editable	 ref="md"  @imgAdd="$imgAdd" @imgAddOrigin="$imgAddOrigin"/>
        </el-row>
        <el-row>
            <el-col :span="24" style="margin-top: 20px">
                <el-button @click="addOrUpdateArtile">{{btnSave}}</el-button>
                <el-button @click="addHistoryArtile">更新到历史版本</el-button>

            </el-col>
        </el-row>
    </div>
    </el-drawer>

</div>
</template>

<script>
import axios from '@/api/ajax.js'
import Table from 'element-ui/lib/table';
import TableColumn from 'element-ui/lib/table-column';
import Vue from "vue/dist/vue.js";
import Pagination from 'element-ui/lib/pagination';
import Message from 'element-ui/lib/message'
import Cookie from 'js-cookie'
import Const from '@/const.js'
import MessageBox from 'element-ui/lib/message-box'

Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Pagination);
export default {
    name: "tes",
    data: () => {
        return {
            currentGroup: "",
            is_public: 0,
            dialogVisible: false,
            type: "",
            types: [],
            limit: 10,
            offset: 0,
            formInline: {
                dockname: '',
                type: ''
            },
            articleCount: 0,
            articleCountAll: 3,
            ruleInline: {
                dockname: [{
                    message: '请输入查询的文章名字',
                    trigger: 'blur'
                }],
                password: [
                    {
                        message: 'Please fill in the password.',
                        trigger: 'blur'
                    },
                    {
                        type: 'string'
                    }
                ]
            },
            data:[],
            currentNode: {},
            data2: [],
            docKey: "",
            docType: 110,
            doc_types: [],
            doc_typess: new Map,
            drawer: false,
            import_file:false,
            currentEditID: -1,
            currentEditTitle:  "",

            currentEditContent: "",
            btnSave: "提交",
            file_add_id:-1,
            file_add_title:"",
            upload_url:"http://127.0.0.1:4596/api/upload_doc",
            uoload_file_name:"",
            fileList: []
        }
    },
    methods: {
        handlePreview(file) {
            console.log("review_file",file);
            console.log(this.fileList)
        },
        submitUpload() {
            console.log(this.$refs)
            console.log(this.fileList)
            this.$refs.upload.submit()
        },
        $imgAddOrigin(pos, $file) {
            // 第一步.将图片上传到服务器.
            var formdata = new FormData();
            formdata.append('image', $file);
            axios({
                url: (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_upload_origin?type=' : 'https://www.testingcloud.club/sapi/api/image_upload_origin?type=') + $file.type.substring(6,) ,
                method: 'post',
                data: formdata,
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
            }).then((url) => {
                var url1 = (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_download/' : 'https://www.testingcloud.club/sapi/api/image_download/') + url.data.url;
                // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
                /**
                    * $vm 指为mavonEditor实例，可以通过如下两种方式获取
                    * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
                    * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
                    */
                this.$refs.md.$img2Url(pos, url1);
            })
        },
        // 绑定@imgAdd event
        $imgAdd(pos, $file) {
            // 第一步.将图片上传到服务器.
            var formdata = new FormData();
            formdata.append('image', $file);
            axios({
                url: (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_upload?type=' : 'https://www.testingcloud.club/sapi/api/image_upload?type=') + $file.type.substring(6,) ,
                method: 'post',
                data: formdata,
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
            }).then((url) => {
                var url1 = (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_download/' : 'https://www.testingcloud.club/sapi/api/image_download/') + url.data.url;
                // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
                /**
                 * $vm 指为mavonEditor实例，可以通过如下两种方式获取
                 * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
                 * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
                 */

                this.$refs.md.$img2Url(pos, url1);
            })
        },
        onBeforeUpload(file)
        {
            console.log(this.fileList)
            console.log(file.name)
            this.uoload_file_name = file.name
            

            this.upload_url = (process.env.NODE_ENV === 'development' ? "http://127.0.0.1:4596/api/upload_doc?parent=" : 'https://www.testingcloud.club/sapi/api/upload_doc?parent=')+ this.file_add_id + "&filename=" + this.uoload_file_name

            return new Promise((resolve, reject) => {
                this.$nextTick(() => {
                    this.upload_url = (process.env.NODE_ENV === 'development' ? "http://127.0.0.1:4596/api/upload_doc?parent=" : 'https://www.testingcloud.club/sapi/api/upload_doc?parent=') + this.file_add_id + "&filename=" + this.uoload_file_name
                resolve()
            })
            })
            console.log("before ",this.upload_url)
        },
        addOrUpdateArtile(){
            if(this.btnSave == "提交"){
                axios.put("article_tree",{
                    title:this.currentEditTitle,
                    content:this.currentEditContent,
                    author:"admin",
                    type: this.currentNode.id,
                    is_public: 1,
                    father: this.currentNode.id,
                    level: this.currentNode.level + 1
                }).then(resp => {
                        console.log(resp)
                        if (resp.data.Status == 0){
                            console.log(this.data)
                            this.currentNode.children.push({
                                level:this.currentNode.level + 1,
                                father: this.currentNode.id,
                                label:this.currentEditTitle,
                                id: resp.data.Data,
                                children:[],

                            })
                            Message.success("插入成功")
                            this.btnSave = "更新"
                            this.currentEditID = resp.data.Data
          
                        }
                    }
                )
            }

            if(this.btnSave == "更新"){
                console.log(this.currentNode)
                axios.post("article_update_tree",{
                    id: this.currentEditID,
                    title:this.currentEditTitle,
                    content:this.currentEditContent,
                    author:"admin",
                    type: this.currentNode.id,
                    is_public: 1,
                    father: this.currentNode.id,
                    level: this.currentNode.level + 1
                }).then(resp => {
                        console.log(resp)
                        if (resp.data.Status == 0){
                            Message.success("更新成功")
                        }
                    }
                )
            }            
        },
        addHistoryArtile() {
            axios.put("article_tree_history", {
                id: this.currentEditID,
                title: this.currentEditTitle,
                content: this.currentEditContent,
                author: "admin",
                type: this.currentNode.id,
                is_public: 1,
                father: this.currentNode.id,
                level: this.currentNode.level + 1
            }).then(resp => {
                console.log(resp)
                if (resp.data.Status == 0) {
                    Message.success("更新成功")
                }
            }
            )
        },
        handleCloseDraw(done) {
            MessageBox.confirm('确认关闭？')
                .then( _ => {
                    done()
                })
                .catch(_ => {});
        },
        edit(node, data){
            this.drawer = true
            this.currentEditID = data.id

            axios.get("article/" + data.id, {
                withCredentials: true
            }).then(
                resp => {
                    console.log(resp.data.Data)
                    this.currentEditTitle =  resp.data.Data.title
                    this.currentEditContent = resp.data.Data.content
                }
            )
            this.btnSave = "更新"
        },
        findChildren(id){
            this.data.forEach(element => {
                console.log(element)
                if(element.id == id){

                }
            });
        },
        remove(node, data) {
            const parent = node.parent
            const children = parent.data.children || parent.data
            const index = children.findIndex(d => d.id === data.id) // 找到在父节点的索引
            if(data.children.length > 0){
                Message.error("请先删除子项")
                return
            }
            MessageBox.confirm('确认删除？')
                .then( _ => {
                    axios.delete('/article_tree/' + data.id, {}).then(response => {
                        if (response.data.Status === 0) {
                            Message.success("删除成功");
                            children.splice(index, 1)
                        }
                    }).catch(reason => {
                        Message.error("网络错误:" + reason);
                    });
                    done();
                }).catch(_ => {})
        },
        generate_show_url(node, data) { 
            console.log(node, 'https://www.testingcloud.club/dist/admin/index.html#/article/' + node.data.id)
            
            MessageBox.alert('<a href=\'https://www.testingcloud.club/dist/admin/index.html#/article/' + node.data.id
                + '\'> 外链</a>' ,
                '生成外链', {
                dangerouslyUseHTMLString: true
            });
        },
        import_file_func(node, data){
            console.log("import_file_func",data.id,node.label,data)
            this.import_file = true
            this.file_add_title = node.label
            this.file_add_id = data.id
            // upload_url:"http://127.0.0.1:4596/api/upload_doc",

        },
        handleTypeSelect(obj) {
            let j = 0;
            let tmp = [];
            for (let len = this.data2.length; j < len; j++) {
                if (this.data2[j].type === obj) {
                    tmp.push(this.data2[j]);
                }
            }
            this.data1 = [];
            j = 0;
            for (let len = tmp.length; j < len; j++) {
                this.data1.push(tmp[j]);
            }
        },
        handlerShow(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => {});
        },
        append(data) {
            console.log(data)
            this.drawer = true
            if (!data.children) {
                this.$set(data, 'children', [])
            }
            this.currentNode = data
            this.currentEditID =  -1
            this.currentEditTitle = ""
            this.currentEditContent = ""
            this.btnSave = "提交"
            console.log(data)
        },
        handleChangePage(page) {
            axios.post('/articles?limit=' + this.limit + '&offset=' + (page - 1) * this.limit, {
                name: this.formInline.user,
                types: this.docType
            }).then(response => {
                this.data1 = [];
                this.data2 = [];
                if (response.data.Status === 0) {
                    let j = 0;
                    for (let len = response.data.Data.length; j < len; j++) {
                        response.data.Data[j].typename = this.doc_typess.get(String(response.data.Data[j].type)).type_name

                        this.data1.push(response.data.Data[j]);
                    }
                }
            }).catch(reason => {
                Message.error("网络错误:" + reason);
            })
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => {})
        },
        handleClick(row) {
            this.$router.push("/article/" + row.row.id);
        },
        handleEdit(row) {
            this.$router.push("/BarIView/editor?id=" + row.row.id);
        },
        handleDelete(row) {
            MessageBox.confirm('确认关闭？')
                .then(_ => {
                    axios.delete('/article/' + row.row.id, {}).then(response => {
                        if (response.data.Status === 0) {
                            let j = 0;
                            for (let len = this.data1.length; j < len; j++) {
                                if (this.data1[j].id == row.row.id) {

                                    this.data1.splice(j, 1)
                                }
                                //this.data1.push(response.data.Data[j]);
                            }
                            Message.success("删除成功");
                        }
                    }).catch(reason => {
                        Message.error("网络错误:" + reason);
                    })
                    done()
                })
                .catch(_ => {});

        },
        getArtileTree(){
            axios.get('/articles_tree').then(response=>{
                if (response.data.Status === 0) {
                    this.data = response.data.Data
                    for(let i = 0;i < (response.data.Data.length) ; i ++){
                        console.log(response.data.Data[i])
                    }

                }
            })
        },
        getArtcleTypes(){
            axios.get("doc_types", {
                withCredentials: true
            }).then(
                resp => {
                    this.doc_types.push({
                        "Id": 110,
                        "type_name": "全部"
                    })
                    let j = 0;
                    for (let typeNum = resp.data.Data.length; j < typeNum; j++) {
                        this.doc_types.push(resp.data.Data[j])
                        this.doc_typess.set(String(resp.data.Data[j]["id"]),resp.data.Data[j])
                    }
                }
            ).catch(
                reason => {
                    Message.error(reason)
                }
            )
        },
        getArticleCount() {
            axios.get('/articleCount', {}).then(response => {
                if (response.data.Status === 0) {
                    this.articleCountAll = response.data.Data.cnt
                    this.articleCount = this.articleCountAll;
                }
            }).catch(reason => {
                Message.error("网络错误:" + reason);
            });
        },
        OnChangeGroup() {
            console.log(this.currentGroup, this.docgroups[this.currentGroup])
            this.getGroupType(this.docgroups[this.currentGroup].Int);
        },
        getGroupType(id) {
            axios.post("/group_type", {
                id: id,
            })
                .then(response => {
                    if (response.data.Status === 0) {
                        console.log(response.data.Data)
                        this.doc_types = response.data.Data;
                        this.docType = this.doc_types[0].id;
                    }
                })
                .catch(reason => {
                    Message.error("网络错误:" + reason);
                });
        },
        getDocGroup() {
            axios.get('/doc_groups', {}).then(response => {
                if (response.data.Status === 0) {
                    console.log(response.data.Data);
                    this.docgroups = response.data.Data;
                } else {}
            }).catch(reason => {
                Message.error("网络错误:" + reason);
            });
        }
    },
    created() {
        this.getArtileTree()
        this.getArtcleTypes()

        console.log(this.Global.ws.send("test for send"))
        this.getDocGroup()
        let userInfo = JSON.parse(Cookie.get(Const.KEY_USER_INFO));
        console.log(userInfo)
        let url = '/user';
        url += 'user=' + userInfo["UserName"]
        url += '&token=' + userInfo["SocketToken"]

        axios.get(url)
            .then(response => {
                console.log(response);
                if (response.data.Status === 0) {
                    
                } else {
                    this.$router.push("/login");
                }
            })
    },
    mounted() {
        this.getArticleCount()
    },
    beforeCreate() {
        
    }
}
</script>

<style scoped>
.el-button--primary:focus,
.el-button--primary:hover {
    background: #DCDFE6;
}
.custom-tree-node {
  justify-content: space-around;
  display:block;
  padding-right: 8px;
  overflow-x: auto;
  overflow-y: auto;
  margin-top: 10px;
}
</style>
